package cn.springbook.common.core.config;

import cn.springbook.common.core.enums.ResultEnum;
import cn.springbook.common.core.expection.BizException;
import cn.springbook.common.core.model.ResponseResult;
import cn.springbook.common.core.model.ResponseResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
　* @description: 全局异常统一处理器
　* @param
　* @return
　* @throws
　* @author caifenglin
　* @date 2021/7/2 17:30
　*/
@ControllerAdvice
public class GlobalExceptionHandler {

	private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	
	/**
	 * 处理自定义的业务异常
	 * @param req
	 * @param e
	 * @return
	 */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody  
	public ResponseResult<Void> exceptionHandler(HttpServletRequest req, BizException e){
    	return ResponseResultUtil.failure(e.getCode(), e.getMessage());
    }

	/**
	 * 处理空指针的异常
	 * @param req
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = NullPointerException.class)
	@ResponseBody
	public ResponseResult<Void> exceptionHandler(HttpServletRequest req, NullPointerException e){
		logger.error("发生空指针异常！原因是:",e);
		return ResponseResultUtil.failure(ResultEnum.FAIL);
	}



    /**
	 * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
	@ResponseBody
	public ResponseResult<Void> exceptionHandler(HttpServletRequest req, Exception e){
    	logger.error("未知异常！原因是:",e);
       	return ResponseResultUtil.failure(ResultEnum.INTERNAL_SERVER_ERROR);
    }
}